package cn.stylefeng.guns.sys.core.util;

import cn.stylefeng.guns.sys.core.constant.cache.CacheKey;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 钉钉类
 *
 * @author zxd
 * @date 2022/03/08 09:30
 */
@Component
public class DingdingUtil {

    // 应用的appKey
    private static String appKey = "dingvvrsivpeg6bqm4qb";
    // 应用的appSecret
    private static String appSecret = "wly_IoMnP0QXZzaWh-NiSOUxZJgpmDzZeKyy6LPQMktm9iO65RfO14LVYUliokL-";
    // access_token url
    private static String accessTokenUrl = "https://oapi.dingtalk.com/gettoken";
    // 考勤记录 url
    private static String attendanceUrl = "https://oapi.dingtalk.com/attendance/list";
    // 部门 url
    private static String departmentUrl = "https://oapi.dingtalk.com/department/list";

    // 员工花名册信息
    private static String USER_ROTA_INFO_URL = "https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/v2/list";


    @Autowired
    private RedisUtils redisUtils;

    /**
     * 通过调用接口获取access_token
     * @return String
     * 2022/03/08 09:30
     */
    public String getAccessToken() {
        String token = (String) redisUtils.get(CacheKey.DINGDING_TOKEN);
        if (ToolUtil.isEmpty(token)) {
            DingTalkClient client = new DefaultDingTalkClient(accessTokenUrl);
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = null;
            try {
                response = client.execute(request);
            } catch (ApiException e) {
                e.printStackTrace();
            }
            token = response.getAccessToken();
            if (ToolUtil.isNotEmpty(token)) {
                redisUtils.set(CacheKey.DINGDING_TOKEN, token,7200);
            }
        }
        return token;
//        DingTalkClient client = new DefaultDingTalkClient(accessTokenUrl);
//        OapiGettokenRequest request = new OapiGettokenRequest();
//        request.setAppkey(appKey);
//        request.setAppsecret(appSecret);
//        request.setHttpMethod("GET");
//        OapiGettokenResponse response = null;
//        try {
//            response = client.execute(request);
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//        return response.getAccessToken();
    }


    /**
     * 判断是否有打卡结果
     * @return OapiAttendanceListResponse
     * 2022/03/08 09:45
     */
    public OapiAttendanceListResponse getAttendanceList(String from, String to, String userId) {
        // 获取access_token
        String access_token = getAccessToken();
        // 通过调用接口获取考勤打卡结果
        DingTalkClient clientDingTalkClient = new DefaultDingTalkClient(attendanceUrl);
        OapiAttendanceListRequest requestAttendanceListRequest = new OapiAttendanceListRequest();
        // 查询考勤打卡记录的起始工作日
        requestAttendanceListRequest.setWorkDateFrom(from);
        // 查询考勤打卡记录的结束工作日
        requestAttendanceListRequest.setWorkDateTo(to);
        // 员工在企业内的userid列表，最多不能超过50个。
        requestAttendanceListRequest.setUserIdList(Arrays.asList(userId));
        // 表示获取考勤数据的起始点
        requestAttendanceListRequest.setOffset(0L);
        // 表示获取考勤数据的条数，最大不能超过50条。
        requestAttendanceListRequest.setLimit(50L);
        OapiAttendanceListResponse response = null;
        try {
            response = clientDingTalkClient.execute(requestAttendanceListRequest, access_token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    public Boolean deleteEmp(String userId) {
        // 获取access_token
        String access_token = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/delete");
        OapiUserDeleteRequest req = new OapiUserDeleteRequest();
        req.setUserid(userId);
        Boolean ret = false;
        try  {
            OapiUserDeleteResponse rsp = client.execute(req, access_token);
            if (rsp.getErrcode() == 0) {
                ret = true;
            }
        }  catch (ApiException e) {
            e.printStackTrace();
        }
        return ret;
    }

    public HashMap<String, Object> deleteEmps(List<String> list) {
        List<String> result = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        if (list.size() > 0) {
            for (String id : list) {
                if (!deleteEmp(id)) {
                    result.add(id);
                }
            }
        }
        if (result.size() > 0) {
            map.put("code", 1);
        } else {
            map.put("code", 0);
        }
        map.put("data", result);
        return map;
    }

    public OapiAttendanceGetcolumnvalResponse.ColumnValListForTopVo getColumnval(String userId, String from, String to) {
        // 获取access_token
        String access_token = getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getcolumnval");
        OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
        req.setUserid(userId);
        // 7100724 上班1打卡时间 7100726 下班1打卡时间 7100728 上班2打卡时间 7100730 下班2打卡时间 7100732 上班3打卡时间 7100734 下班3打卡时间7100736 关联的审批单
        req.setColumnIdList("7100724,7100726,7100728,7100730,7100732,7100734,7100736");
        req.setFromDate(StringUtils.parseDateTime(from));
        req.setToDate(StringUtils.parseDateTime(to));
        OapiAttendanceGetcolumnvalResponse response = null;
        OapiAttendanceGetcolumnvalResponse.ColumnValListForTopVo ret = null;
        try {
            response = client.execute(req, access_token);
            if (response.isSuccess()) {
                ret = response.getResult();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 获取东更道部门信息，
     * 529205900 固定为东更道总部的部门id
     * @return OapiAttendanceListResponse
     * 2022-03-13
     */
    public List getRotaInfoList(String useridList){
        List resultList = new ArrayList<>();
        DingTalkClient client = new DefaultDingTalkClient(USER_ROTA_INFO_URL);
        OapiSmartworkHrmEmployeeV2ListRequest req = new OapiSmartworkHrmEmployeeV2ListRequest();
        req.setUseridList(useridList);
        req.setFieldFilterList("sys02-certNo");
        req.setAgentid(1L);
        String token = getAccessToken();
        OapiSmartworkHrmEmployeeV2ListResponse rsp = null;
        try {
            rsp = client.execute(req, token);
            if (rsp.isSuccess()) {
                resultList = rsp.getResult();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    /**
     * 昨日某个员工打卡记录
     * @return List
     * 2022/03/08 11:00
     */
    public List getRecordByUserId(String userId) {
        String yestoday = DingdingUtil.getYestoday();
        String from = yestoday + " 00:00:00";
        String to = yestoday + " 23:59:59";
        List<OapiAttendanceListResponse.Recordresult> list = new ArrayList();
        OapiAttendanceListResponse attendanceListResponse = getAttendanceList(from, to, userId);
        if (attendanceListResponse.isSuccess() && attendanceListResponse.getRecordresult().size() > 0) {
            list = attendanceListResponse.getRecordresult();
        }
        return list;
    }

    /*时间函数*/
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String result = format.format(today);
        return result;
    }

    /**
     * 昨日日期
     *
     * @return
     */

    public static String getYestoday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }

    /**
     * 获取上午下午
     *
     * @param seconds
     * @return
     */
    public static String timestamp2A(Long seconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("a");
        return sdf.format(new Date(seconds));
    }

    /**
     * 获取年
     *
     * @return
     */
    public static String getYear() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Date date = new Date();
        return format.format(date);
    }

    /**
     * 时间戳转换成时间格式字符串
     *
     * @param seconds
     * @return
     */
    public static String timestamp2Time(Long seconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date(seconds));
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
       ParsePosition pos = new ParsePosition(0);
       Date strtodate = formatter.parse(strDate, pos);
       return strtodate;
    }

    public static String dateToHms(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    /*时间函数*/
}
